package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {

    @Resource
    private AgencyCertificationAuditMapper agencyCertificationAuditMapper;

    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId())
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commit(AgencyCertificationAuditAddReqDTO auditAddReqDTO) {
        // 1.更新机构认证信息表
        Long id = auditAddReqDTO.getServeProviderId();
        AgencyCertification entity = BeanUtil.toBean(auditAddReqDTO, AgencyCertification.class);
        entity.setId(id);
        entity.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        if (ObjectUtil.isNull(super.getById(id))) {
            save(entity);
        } else {
            updateById(entity);
        }

        // 2.更新机构认证审核表
        AgencyCertificationAudit audit = BeanUtil.toBean(entity, AgencyCertificationAudit.class);
        audit.setId(null);
        audit.setServeProviderId(entity.getId());
        audit.setCreateTime(LocalDateTime.now());
        audit.setUpdateTime(LocalDateTime.now());
        agencyCertificationAuditMapper.insert(audit);
    }

    @Override
    public RejectReasonResDTO rejectReason(Long userId) {
        AgencyCertificationAudit audit = agencyCertificationAuditMapper.selectOne(
                Wrappers.<AgencyCertificationAudit>lambdaQuery()
                        .eq(AgencyCertificationAudit::getId, userId)
                        .eq(AgencyCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                        .orderByDesc(AgencyCertificationAudit::getUpdateTime)
        );
        return audit == null ? null : new RejectReasonResDTO(audit.getRejectReason());
    }

    @Override
    public PageResult<AgencyCertificationAuditResDTO> getPage(AgencyCertificationAuditPageQueryReqDTO pageQueryReqDTO, Long auditorId, String auditorName) {
        String name = pageQueryReqDTO.getName();
        String legalPersonName = pageQueryReqDTO.getLegalPersonName();
        Integer auditStatus = pageQueryReqDTO.getAuditStatus();
        Integer certificationStatus = pageQueryReqDTO.getCertificationStatus();
        Page<AgencyCertificationAudit> page = PageUtils.parsePageQuery(pageQueryReqDTO, AgencyCertificationAudit.class);
        Page<AgencyCertificationAudit> auditPage = agencyCertificationAuditMapper.selectPage(page,
                Wrappers.<AgencyCertificationAudit>lambdaQuery()
                        .like(StringUtils.isNoneBlank(name), AgencyCertificationAudit::getName, ("%" + name + "%"))
                        .like(StringUtils.isNoneBlank(legalPersonName), AgencyCertificationAudit::getLegalPersonName, ("%" + legalPersonName + "%"))
                        .eq(ObjectUtil.isNotNull(auditStatus), AgencyCertificationAudit::getAuditStatus, auditStatus)
                        .eq(ObjectUtil.isNotNull(certificationStatus), AgencyCertificationAudit::getCertificationStatus, certificationStatus)
        );
        return PageUtils.toPage(auditPage, AgencyCertificationAuditResDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Long id, Integer certificationStatus, String rejectReason, Long auditorId, String auditorName) {
        AgencyCertificationAudit audit = agencyCertificationAuditMapper.selectById(id);
        if (ObjectUtil.isNull(audit)) {
            throw new BadRequestException("认证信息不存在");
        }
        // 更新机构认证审核表
        if (certificationStatus == CertificationStatusEnum.SUCCESS.getStatus()) {
            // 1.审核通过
        } else if (certificationStatus == CertificationStatusEnum.FAIL.getStatus()) {
            // 2.审核不通过
            audit.setRejectReason(rejectReason);
        } else {
            throw new BadRequestException("认证状态异常");
        }
        audit.setAuditStatus(AuditStatusEnum.YES.getStatus());
        audit.setAuditorId(auditorId);
        audit.setAuditorName(auditorName);
        audit.setAuditTime(LocalDateTime.now());
        audit.setCertificationStatus(certificationStatus);
        agencyCertificationAuditMapper.updateById(audit);

        // 更新机构认证信息表
        AgencyCertification entity = BeanUtil.toBean(audit, AgencyCertification.class);
        entity.setId(audit.getServeProviderId());
        entity.setCertificationTime(LocalDateTime.now());
        boolean ret = super.updateById(entity);
        if (!ret) {
            throw new BadRequestException("更新机构认证信息异常");
        }
    }
}
